package com.xlh.util;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apdplat.word.analysis.CosineTextSimilarity;
import org.apdplat.word.analysis.TextSimilarity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author cheer
 */
public class DocCheckUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DocCheckUtil.class);

    public static Double similarity(String filePathA, String filePathB) {
        String textA = parseDoc(filePathA);
        String textB = parseDoc(filePathB);
        TextSimilarity textSimilarity = new CosineTextSimilarity();
        return textSimilarity.similarScore(textA, textB);
    }

    public static Double similarityString(String strA, String strB) {
        TextSimilarity textSimilarity = new CosineTextSimilarity();
        return textSimilarity.similarScore(strA, strB);
    }

    public static String parseDoc(String filePath) {
        String text = null;
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(filePath);
            inputStream = FileMagic.prepareToCheckMagic(inputStream);

            if (FileMagic.valueOf(inputStream) == FileMagic.OLE2) {
                //word 2003： 图片不会被读取
                try (WordExtractor wordExtractor = new WordExtractor(inputStream);) {
                    text = wordExtractor.getText();
                }

            } else if (FileMagic.valueOf(inputStream) == FileMagic.OOXML) {
                //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
                try (XWPFDocument doc = new XWPFDocument(inputStream);
                     XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) {
                    text = extractor.getText();
                }
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }

        return text;
    }
}
